
package com.course.business.controller.web.discusspost;

import com.course.server.domain.Member;
import com.course.server.domain.discusspost.DiscussPost;
import com.course.server.dto.PageDto;
import com.course.server.dto.ResponseDto;
import com.course.server.dto.discusspost.DiscussPostDto;
import com.course.server.service.MemberService;
import com.course.server.service.discusspost.ElasticsearchService;
import com.course.server.service.discusspost.LikeService;
import com.course.server.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/web")
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private LikeService likeService;

    // search/xxx
    @RequestMapping(path = "/search/{keyword}")
    public ResponseDto search(@PathVariable("keyword") String keyword,@RequestBody PageDto pageDto) throws IOException {
        ResponseDto responseDto = new ResponseDto();
        // 搜索帖子
        List<DiscussPost> searchResult =
                elasticsearchService.searchDiscussPost(keyword, (pageDto.getPage()-1)*pageDto.getSize(), pageDto.getSize(),pageDto);

        List<DiscussPostDto> discussPostDtoList=new ArrayList<>();
        for (DiscussPost discussPost : searchResult) {
            DiscussPostDto discussPostDto=new DiscussPostDto();
            discussPostDto.setDiscussPost(discussPost);
            long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
            discussPostDto.setLikeCount(likeCount);
            Member user = memberService.findUserById(discussPost.getUserId());
            discussPostDto.setUser(user);
            discussPostDtoList.add(discussPostDto);
        }
        Map<String,Object> dto=new HashMap<>();
        dto.put("discussPosts", discussPostDtoList);
        dto.put("keyword", keyword);
        pageDto.setMap(dto);

        responseDto.setContent(pageDto);
        return responseDto;
    }

}
